#include <string.h>
#include "ad768x.h"
#include "esp_log.h"

#define DMA_CHAN        2
#define PIN_NUM_MISO    12
#define PIN_NUM_MOSI    13
#define PIN_NUM_CLK     14
#define PIN_NUM_CS      15

uint8_t dummy_char[1] = {0};
uint16_t dummy_len = 1;
uint8_t dummy_uint8 = 0;

spi_device_handle_t spi;

#define AD7682_CMD_READ 0xFA04

spi_transaction_t t;
// uint16_t data;

// const uint8_t cmd[2] = {0xFA,0x04};//ad7682 IN5
const uint8_t cmd[2] = {0xF4,0x04};//ad7682 IN2
const uint8_t ch_config[8][2] = {
    {0xF0,0x04},
    {0xF2,0x04},
    {0xF4,0x04},
    {0xF6,0x04},
    {0xF8,0x04},
    {0xFA,0x04},
    {0xFC,0x04},
    {0xFE,0x04},
};

uint16_t read_ad768x_data_one_data() {
    esp_err_t ret;
    ret = spi_device_transmit(spi, &t);
    // ESP_LOGI("ret: ", " : %d ", ret);


    assert(ret == ESP_OK);
    // ESP_LOGI("arr: ", " : %x : %x : %x : %x", t.rx_data[0],t.rx_data[1],t.rx_data[2],t.rx_data[3]);
    uint16_t data_assignment =  ((t.rx_data[1]) | (t.rx_data[0])<< 8);   
    return data_assignment;
}

uint16_t read_ad768x_data_one_data_on_chs(uint8_t adc_ch_counter) {
    esp_err_t ret;

    t.tx_buffer = &ch_config[adc_ch_counter][0];

    ret = spi_device_transmit(spi, &t);
    // ESP_LOGI("ret: ", " : %d ", ret);

    assert(ret == ESP_OK);
    // ESP_LOGI("arr: ", " : %x : %x : %x : %x", t.rx_data[0],t.rx_data[1],t.rx_data[2],t.rx_data[3]);
    uint16_t data_assignment =  ((t.rx_data[1]) | (t.rx_data[0])<< 8);   
    return data_assignment;
}


static void spi_init(){
    esp_err_t ret;
       //    spi_device_handle_t handle;

    // Configuration for the SPI bus
    spi_bus_config_t buscfg = {
        .mosi_io_num = PIN_NUM_MOSI,
        .miso_io_num = PIN_NUM_MISO ,
        .sclk_io_num = PIN_NUM_CLK,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1
    };

    // Configuration for the SPI device on the other side of the bus
    spi_device_interface_config_t devcfg = {
        .clock_speed_hz = 4000000,
        .mode = 0,
        .spics_io_num = PIN_NUM_CS,
        .queue_size = 4
    };

    //Initialize the SPI bus
    ret = spi_bus_initialize(SPI2_HOST, &buscfg, SPI_DMA_CH_AUTO);
    ESP_ERROR_CHECK(ret);
    ret = spi_bus_add_device(SPI2_HOST, &devcfg, &spi);
    ESP_ERROR_CHECK(ret);

    memset(&t, 0, sizeof(t));
    t.flags = SPI_TRANS_USE_RXDATA;
    t.length = 16; // 16位数据
    t.rxlength = 16; // 读取16位数据
    t.tx_buffer = cmd;

}

void ad768x_init(void){
    spi_init();
}
